<?php

namespace App\Repositories;

use App\Traits\ApiRespond;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class Repository
{
    use ApiRespond;

    protected $token = '';
    protected $request;

    protected $page;
    protected $page_size;

    public function __construct(Request $request)
    {

        $this->request = $request;
        $this->page_size = $request->input('page_size', 10);
        $this->page = $request->input('page', 1);
    }

    /**
     *
     * 获取管理员信息
     * @author Paco
     * @createTime 2018/8/20 12:08
     * @return mixed
     */
    public function getAdmin($check = false)
    {
        $key = 'token_' . $this->getToken();
        $info = app('phpredis')->get($key);
        $info = json_decode($info);
        if ($check) {
            if (!$info || !$info->admin_id) {
                $this->throwRespondError(10309);
            }
        }
        return $info;
    }


    /**
     * 获取用户信息
     * @author: Pako
     * @Email: admin@jqcool.net
     * @Date: 18-10-24 下午9:53
     */
    public function getUser()
    {
        $user = $this->getAdmin();
        if (!$user || !$user->user_id) {
            $this->throwRespondError(10309);
        }
        return $user;
    }


    /**
     *
     * 获取token
     * @author Paco
     * @createTime 2018/8/20 12:08
     */
    public function getToken()
    {
        $token = $this->request->header('Authorization');
        if (!$token) {
            return false;
        }
        $token = explode(' ', $token);
        if (count($token) < 2) {
            return false;
        }
        return $token[1];
    }


    public function getIP()
    {
        return $this->request->getClientIp();
    }

    /**
     *
     * 记录日志
     * @author Paco
     * @createTime 2018/8/20 12:08
     * @param $desc
     * @param string $data
     */
    public function log_done($desc, $data = '')
    {

        $info = $this->getAdmin();
        $ip = $this->request->getClientIp();
        log_done($info->admin_id, $info->admin_name, $desc, $ip, json_encode($data));
    }
}
